package com.mantru.iotpot.Home;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;

import com.mantru.iotpot.ApplicationClass;
import com.mantru.iotpot.Cleaning.PotCuringActivity;
import com.mantru.iotpot.Cook.ManualCookActivity;
import com.mantru.iotpot.DateClass.FoodList;
import com.mantru.iotpot.Cleaning.CleanWayActivity;
import com.mantru.iotpot.R;
import com.mantru.iotpot.Tools.LoadingDialogUtil;
import com.mantru.iotpot.Util.ToastUtils;
import com.mantru.iotpot.dishes.DishesShowActivity;
import com.mantru.iotpot.eventbus.EventMessage;
import com.mantru.iotpot.setting.CleaningPipeActivity;
import com.mantru.iotpot.setting.SettingActivity;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class HomeActivity extends AppCompatActivity implements View.OnClickListener {

    private ApplicationClass ac;
    private int count = 14;
    private List<FoodList> vegetableList = new ArrayList<>();
    private Handler handler; // 用于定时任务
    private ImageView internet;
    private TextView textView;
    private ImageView condition;
    private int currentNetStatus; // 当前网络状态
    private int net;
    private TextView homewen;
    private String pipe_name = "";
    private GridView gridView;
    private String TAG = "HomeActivity";
    private TextView error_text;
    private ImageView error_img;
    private TextView wifi_name;
    private WifiManager wifiManager;
    private String connectedWifiName;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main6);
        ac = (ApplicationClass) getApplication(); // 初始化 ApplicationClass
        wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
        pipe_name = ac.GetSQLData_Cleaning_Nozzle_GetNameList();
        gridView = findViewById(R.id.gridView);

        findViewById(R.id.home_button2).setOnClickListener(this);
        findViewById(R.id.home_button1).setOnClickListener(this);
        findViewById(R.id.home_button3).setOnClickListener(this);
        findViewById(R.id.home_button4).setOnClickListener(this);
        findViewById(R.id.home_button5).setOnClickListener(this);
        wifi_name = findViewById(R.id.home_text1);
        internet = findViewById(R.id.wifi);
        textView = findViewById(R.id.home_text2);
        condition = findViewById(R.id.home_star1);
        homewen = findViewById(R.id.home_text4);
        error_text = findViewById(R.id.home_text3);
        error_img = findViewById(R.id.home_zhuyi);
        currentNetStatus = ac.net_work_status; // 获取当前网络状态
        updateNetworkUI(currentNetStatus); // 更新网络状态
        handler = new Handler(); // 初始化 Handler
        startNetworkCheck(); // 启动定时任务，每隔1秒检查网络状态

    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.home_button1) { // 洗锅
            LoadingDialogUtil.showLoadingDialog(HomeActivity.this);
            startActivity(new Intent(this, CleanWayActivity.class));
        } else if (v.getId() == R.id.home_button2) {
            LoadingDialogUtil.showLoadingDialog(HomeActivity.this);
            startActivity(new Intent(this, ManualCookActivity.class));
        } else if (v.getId() == R.id.home_button3) { // 菜谱研发
            LoadingDialogUtil.showLoadingDialog(HomeActivity.this);
            startActivity(new Intent(this, DishesShowActivity.class));
        } else if (v.getId() == R.id.home_button4) {
            LoadingDialogUtil.showLoadingDialog(HomeActivity.this);
            startActivity(new Intent(this, PotCuringActivity.class));
        } else if (v.getId() == R.id.home_button5) {
            LoadingDialogUtil.showLoadingDialog(HomeActivity.this);
            startActivity(new Intent(this, SettingActivity.class));
        }
    }

    // 启动定时任务
    private void startNetworkCheck() {
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                checkNetworkStatus(); // 检查网络状态
                setwendu(); // 检查温度
                ac.SaveLog("net_work_status=" + ac.net_work_status);
                if (ac.error_desc.length() > 0){
                    error_img.setVisibility(View.VISIBLE);
                    error_text.setText(ac.error_desc);
                    error_text.setVisibility(View.VISIBLE);
                }else {
                    error_img.setVisibility(View.GONE);
                    error_text.setVisibility(View.GONE);
                }
                // 每隔1秒重复执行
                handler.postDelayed(this, 1000);
            }
        }, 1000);
    }

    // 检查网络状态
    private void checkNetworkStatus() {
        net = ac.net_work_status;
        Log.d("net", "net: " + net);
        if (net != currentNetStatus) { // 只有在网络状态变化时才更新UI
            currentNetStatus = net;
            updateNetworkUI(net);
        }
    }

    // 更新网络状态UI
    private void updateNetworkUI(int net) {
        if (net == 0) {
            // 网络异常
            Log.e("Network", "网络异常");
            textView.setText("不在线");
            internet.setImageResource(R.drawable.nowifi);
            condition.setImageResource(R.drawable.star2);
            wifi_name.setVisibility(View.INVISIBLE);
        } else if (net == 1) {
            // 网络正常
            Log.i("Network", "网络正常");
            textView.setText("在线");
            internet.setImageResource(R.drawable.wifi);
            condition.setImageResource(R.drawable.stat1);
            wifi_name.setVisibility(View.VISIBLE);
            wifi_name.setText(getCurrentWifiName());
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 移除所有回调，避免内存泄漏
        if (handler != null) {
            handler.removeCallbacksAndMessages(null);
        }
        System.out.println("系统退出");
        // 关闭线程
        ac.app_is_release = true;
        ac.APP_Release();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // 检查是否是返回键
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            // 拒绝返回键的默认行为
            return true;
        }
        // 其他按键事件仍按默认处理
        return super.onKeyDown(keyCode, event);
    }

    public void setwendu() {
        if (ac.pot_temperature_is_error){
//            homewen.setText("传感器故障");
            homewen.setVisibility(View.INVISIBLE);
        }else {
            int wendu = ac.pot_temperature_value;
            homewen.setText("锅温:" + String.valueOf(wendu) + "℃");
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventBusMessage(EventMessage event) {
        if (event.id == EventMessage.MSG_ID_CleaningTishi) {
            showDialog();
        } else if (event.id == EventMessage.MSG_ID_ErrorInfo) {//收到故障之后
            ac.SaveLog("已经收到故障消息");
            try {
                // 解析 JSON 数据
                JSONObject json = new JSONObject(event.message);
                String errorCode = json.getString("error_code");
                String errorDesc = json.getString("error_desc");
                Log.d(TAG, "Error Code: " + errorCode);
                Log.d(TAG, "Error Desc: " + errorDesc);
                Intent intent = new Intent(this, ErrorActivity.class);
                intent.putExtra("error_code",errorCode);
                intent.putExtra("error_desc",errorDesc);
                ac.SaveLog("已从主页传参数过去了。error_code: " + errorCode + " error_desc: " + errorDesc);
                startActivity(intent);
                // 根据 needCode 做其他处理
            } catch (JSONException e) {
                Log.e(TAG, "Error parsing JSON: " + e.getMessage());
                ac.SaveLog("解析故障消息出错，错误原因：" + e.getMessage());
            }
        } else if (event.id == EventMessage.MSG_ID_OnSyncVegetable) {//收到远程同步的消息之后
            ac.SaveLog("收到远程同步的消息");
            // 立即显示加载弹窗（确保用户感知加载过程）
            LoadingDialogUtil.showLoadingDialog(HomeActivity.this);
            ExecutorService executor = Executors.newSingleThreadExecutor();
            executor.execute(() -> {
                // 1. 后台线程处理数据解析
                String json_data = ac.GetSQLData_Vegetable_List(count);
                List<FoodList> tempList = new ArrayList<>(); // 使用临时列表避免并发问题
                try {
                    JSONObject jsonObject = new JSONObject(json_data);
                    if (jsonObject.getBoolean("success")) {
                        JSONArray itemDataArray = jsonObject.getJSONArray("item_data");
                        for (int i = 0; i < itemDataArray.length(); i++) {
                            JSONObject vegetableJson = itemDataArray.getJSONObject(i);
                            String vegetableId = vegetableJson.getString("vegetable_id");
                            String vegetableName = vegetableJson.getString("vegetable_name");
                            String faceImageUrl = vegetableJson.getString("face_image_url")
                                    .replace("file:///", "");
                            tempList.add(new FoodList(vegetableId, vegetableName, faceImageUrl));
                        }
                    }
                } catch (Exception e) {
                    Log.e("HomeActivity", "数据加载失败", e);
                    runOnUiThread(() ->
                            Toast.makeText(this, "加载失败，请重试", Toast.LENGTH_SHORT).show()
                    );
                }

                // 2. 主线程更新 UI（确保所有数据操作完成）
                runOnUiThread(() -> {
                    vegetableList.clear();
                    vegetableList.addAll(tempList);
                    vegetableList.add(new FoodList("more", "查看更多", "")); // 在主线程添加

                    if (adapter == null) {
                        // 首次初始化适配器
                        adapter = new GridAdapter(HomeActivity.this, vegetableList);
                        gridView.setAdapter(adapter);
                        gridView.setNumColumns(3);
                    } else {
                        // 数据变化时刷新
                        adapter.notifyDataSetChanged();
                    }

                    // 3. 数据渲染完成后再关闭弹窗
                    LoadingDialogUtil.closeLoadingDialog();
                    try {
                        JSONObject data = new JSONObject(event.message);
                        ac.SaveLog("收到远程同步的消息的json： " + event.message);
                        String toas = data.getString("msg");
                        ToastUtils.show(this,toas);
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                });

                executor.shutdown();
            });
            ToastUtils.show(this,event.message);
        }
    }

    // 显示弹窗
    private void showDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        LayoutInflater inflater = getLayoutInflater();
        View dialogView = inflater.inflate(R.layout.home_dialog, null);
        TextView dialog_text = dialogView.findViewById(R.id.home_dialog_text);
        Button cancle = dialogView.findViewById(R.id.home_dialog_cancle);
        Button confirm = dialogView.findViewById(R.id.home_dialog_confirm);
        builder.setView(dialogView);
        AlertDialog dialog = builder.create();
        dialog_text.setText(pipe_name + "\n料管可清洗");
        cancle.setOnClickListener(v -> { // 返回首页
            dialog.dismiss();
        });
        confirm.setOnClickListener(v -> {
            startActivity(new Intent(this, CleaningPipeActivity.class));
            dialog.dismiss();
        });
        dialog.show();
        // 关键代码：设置窗口背景透明
        if (dialog.getWindow() != null) {
            dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        }
        // 关键代码：设置点击外部不可取消
        dialog.setCanceledOnTouchOutside(false);
    }

    // 在Activity可见时注册EventBus
    @Override
    protected void onStart() {
        super.onStart();
        EventBus.getDefault().register(this);
        LocalBroadcastManager.getInstance(this).registerReceiver(receiver, new IntentFilter("ACTION_CLOSE_LOADING_DIALOG"));
    }

    @Override
    protected void onStop() {
        super.onStop();
        EventBus.getDefault().unregister(this);
        LocalBroadcastManager.getInstance(this).unregisterReceiver(receiver);
    }

    private GridAdapter adapter; // 将 adapter 提升为成员变量

    @Override
    protected void onResume() {
        super.onResume();

        // 立即显示加载弹窗（确保用户感知加载过程）
        LoadingDialogUtil.showLoadingDialog(HomeActivity.this);

        ExecutorService executor = Executors.newSingleThreadExecutor();
        executor.execute(() -> {
            // 1. 后台线程处理数据解析
            String json_data = ac.GetSQLData_Vegetable_List(count);
            Log.d(TAG,"json_data: " + json_data);
            List<FoodList> tempList = new ArrayList<>(); // 使用临时列表避免并发问题

            try {
                JSONObject jsonObject = new JSONObject(json_data);
                if (jsonObject.getBoolean("success")) {
                    JSONArray itemDataArray = jsonObject.getJSONArray("item_data");
                    for (int i = 0; i < itemDataArray.length(); i++) {
                        JSONObject vegetableJson = itemDataArray.getJSONObject(i);
                        String vegetableId = vegetableJson.getString("vegetable_id");
                        String vegetableName = vegetableJson.getString("vegetable_name");
                        String faceImageUrl = vegetableJson.getString("face_image_url")
                                .replace("file:///", "");
                        tempList.add(new FoodList(vegetableId, vegetableName, faceImageUrl));
                    }
                }
            } catch (Exception e) {
                Log.e("HomeActivity", "数据加载失败", e);
                runOnUiThread(() ->
                        Toast.makeText(this, "加载失败，请重试", Toast.LENGTH_SHORT).show()
                );
            }

            // 2. 主线程更新 UI（确保所有数据操作完成）
            runOnUiThread(() -> {
                vegetableList.clear();
                vegetableList.addAll(tempList);
                vegetableList.add(new FoodList("more", "查看更多", "")); // 在主线程添加

                if (adapter == null) {
                    // 首次初始化适配器
                    adapter = new GridAdapter(HomeActivity.this, vegetableList);
                    gridView.setAdapter(adapter);
                    gridView.setNumColumns(3);
                } else {
                    // 数据变化时刷新
                    adapter.notifyDataSetChanged();
                }

                // 3. 数据渲染完成后再关闭弹窗
                LoadingDialogUtil.closeLoadingDialog();
            });

            executor.shutdown();
        });
    }

    //广播接收器定义（用于接收关闭弹窗的消息）
    private BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if ("ACTION_CLOSE_LOADING_DIALOG".equals(intent.getAction())) {
                LoadingDialogUtil.closeLoadingDialog();//关闭弹窗
            }
        }
    };

    public String getCurrentWifiName() {
        WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
        WifiInfo wifiInfo = wifiManager.getConnectionInfo();
        String ssid = wifiInfo.getSSID();
        if (ssid != null && ssid.startsWith("\"") && ssid.endsWith("\"")) {
            ssid = ssid.substring(1, ssid.length() - 1);
        }
        return ssid;
    }

}